<?php
/**
 * 路由处理类
 */

class Router {
    private $routes = [];
    
    public function __construct() {
        $this->registerRoutes();
    }
    
    private function registerRoutes() {
        // 用户相关路由
        $this->routes['/user/login'] = ['UserController', 'login'];
        $this->routes['/user/register'] = ['UserController', 'register'];
        $this->routes['/user/info'] = ['UserController', 'getUserInfo'];
        $this->routes['/user/health'] = ['UserController', 'updateHealthInfo'];
        
        // 食材相关路由
        $this->routes['/food/list'] = ['FoodController', 'getFoodList'];
        $this->routes['/food/search'] = ['FoodController', 'searchFood'];
        $this->routes['/food/detail'] = ['FoodController', 'getFoodDetail'];
        $this->routes['/food/categories'] = ['FoodController', 'getCategories'];
        
        // 食谱相关路由
        $this->routes['/recipe/recommend'] = ['RecipeController', 'getRecommendation'];
        $this->routes['/recipe/daily'] = ['RecipeController', 'getDailyRecipe'];
        $this->routes['/recipe/detail'] = ['RecipeController', 'getRecipeDetail'];
        $this->routes['/recipe/custom'] = ['RecipeController', 'createCustomRecipe'];
        
        // 健康数据路由
        $this->routes['/health/record'] = ['HealthController', 'recordHealthData'];
        $this->routes['/health/history'] = ['HealthController', 'getHealthHistory'];
        $this->routes['/health/analysis'] = ['HealthController', 'getHealthAnalysis'];
    }
    
    public function handle($path, $method, $data) {
        // 处理根路径
        if ($path === '/' || $path === '') {
            return apiSuccess(['message' => '健康营养食谱API服务运行正常', 'version' => '1.0.0']);
        }
        
        // 查找匹配的路由
        if (isset($this->routes[$path])) {
            list($controllerName, $methodName) = $this->routes[$path];
            
            // 检查控制器文件是否存在
            $controllerFile = __DIR__ . '/' . $controllerName . '.php';
            if (!file_exists($controllerFile)) {
                throw new Exception("控制器 {$controllerName} 不存在");
            }
            
            require_once $controllerFile;
            
            // 实例化控制器
            $controller = new $controllerName();
            
            // 检查方法是否存在
            if (!method_exists($controller, $methodName)) {
                throw new Exception("方法 {$methodName} 不存在");
            }
            
            // 调用控制器方法
            return $controller->$methodName($data);
        }
        
        // 未找到路由
        return apiError('接口不存在', 404);
    }
}

?>